const express = require('express');
const router = express.Router();
const db = require('../config/database');

// ========== 代拿员认证接口（根据详细设计文档） ==========

/**
 * 代拿员认证接口 - 基于手机号自动认证
 * 根据详细设计文档3.4节实现
 */
router.post('/certification', async (req, res) => {
    const { userId, realName, studentId, phone } = req.body;
    console.log('📋 代拿员认证申请，用户ID:', userId);

    // 步骤1：参数验证
    if (!userId || !realName || !studentId || !phone) {
        return res.status(400).json({
            success: false,
            errorCode: 4001,
            errorMessage: '认证信息不完整：需要userId、realName、studentId和phone'
        });
    }

    // 步骤2：手机号格式验证
    const phoneRegex = /^1\d{10}$/;
    if (!phoneRegex.test(phone)) {
        return res.status(400).json({
            success: false,
            errorCode: 4002,
            errorMessage: '手机号格式不正确'
        });
    }

    // 步骤3：学号格式验证
    if (!studentId || studentId.length < 6 || studentId.length > 20 || !/^\d+$/.test(studentId)) {
        return res.status(400).json({
            success: false,
            errorCode: 4002,
            errorMessage: '学号格式不正确（应为6-20位数字）'
        });
    }

    // 步骤4：姓名格式验证（2-10个汉字）
    const nameRegex = /^[\u4e00-\u9fa5]{2,10}$/;
    if (!nameRegex.test(realName)) {
        return res.status(400).json({
            success: false,
            errorCode: 4002,
            errorMessage: '姓名格式不正确（应为2-10个汉字）'
        });
    }

    try {
        // 步骤5：重复认证检查
        const [existingCouriers] = await db.execute(
            'SELECT id, status FROM courier_users WHERE user_id = ?',
            [userId]
        );

        if (existingCouriers.length > 0) {
            // 检查是否已通过认证
            if (existingCouriers[0].status === 'active' || existingCouriers[0].status === 1) {
                return res.json({
                    success: false,
                    errorCode: 4201,
                    errorMessage: '已是认证代拿员'
                });
            }
        }

        // 步骤6：检查手机号是否已被其他用户使用
        const [existingUsers] = await db.execute(
            'SELECT id FROM users WHERE phone = ? AND id != ?',
            [phone, userId]
        );

        if (existingUsers.length > 0) {
            return res.status(400).json({
                success: false,
                errorCode: 4201,
                errorMessage: '手机号已被其他用户使用'
            });
        }

        // 步骤7：验证手机号归属（简化版：检查是否为常见号段）
        const commonPrefixes = ['138', '139', '150', '151', '152', '157', '158', '159',
            '182', '183', '184', '187', '188', '130', '131', '132',
            '155', '156', '185', '186', '145', '147', '170', '171',
            '173', '175', '176', '177', '178', '180', '181', '189'];
        const phonePrefix = phone.substring(0, 3);
        const isValidPrefix = commonPrefixes.includes(phonePrefix);

        if (!isValidPrefix) {
            console.warn('⚠️ 非常见手机号段:', phone);
            // 仍允许通过，但记录日志
        }

        // 步骤8：创建或更新代拿员记录（自动通过认证）
        const conn = await db.getConnection();
        try {
            await conn.beginTransaction();

            let courierId;
            if (existingCouriers.length > 0) {
                // 更新现有记录
                await conn.execute(
                    `UPDATE courier_users SET 
                        student_id = ?,
                        status = 'active',
                        credit_score = 100,
                        total_orders = COALESCE(total_orders, 0),
                        completed_orders = COALESCE(completed_orders, 0),
                        avg_rating = 5.0
                     WHERE user_id = ?`,
                    [studentId, userId]
                );
                courierId = existingCouriers[0].id;
            } else {
                // 创建新记录
                const [result] = await conn.execute(
                    `INSERT INTO courier_users 
                        (user_id, student_id, credit_score, total_orders, completed_orders, avg_rating, status)
                     VALUES (?, ?, 100, 0, 0, 5.0, 'active')`,
                    [userId, studentId]
                );
                courierId = result.insertId;
            }

            // 步骤9：更新用户手机号（如果与当前登录手机号不同）
            const [currentUser] = await conn.execute(
                'SELECT phone FROM users WHERE id = ?',
                [userId]
            );

            if (currentUser.length > 0 && currentUser[0].phone !== phone) {
                await conn.execute(
                    'UPDATE users SET phone = ?, is_phone_verified = 1 WHERE id = ?',
                    [phone, userId]
                );
            }

            // 步骤10：更新用户角色（如果当前不是代拿员角色）
            const [userRole] = await conn.execute(
                'SELECT role FROM users WHERE id = ?',
                [userId]
            );

            if (userRole.length === 0 || (userRole[0].role !== 'courier' && userRole[0].role !== 'courier_user')) {
                await conn.execute(
                    'UPDATE users SET role = ? WHERE id = ?',
                    ['courier', userId]
                );
            }

            await conn.commit();

            console.log('✅ 代拿员认证成功，用户ID:', userId, '代拿员ID:', courierId);

            // 步骤11：返回认证结果
            res.json({
                success: true,
                message: '代拿员认证成功',
                data: {
                    certificationId: courierId,
                    status: 'approved',
                    currentStep: 'completed',
                    permissions: ['接单', '查看订单', '更新状态', '收益提现'],
                    courierInfo: {
                        id: courierId,
                        studentId: studentId,
                        creditScore: 100,
                        status: 'active'
                    }
                }
            });

        } catch (error) {
            await conn.rollback();
            throw error;
        } finally {
            conn.release();
        }

    } catch (error) {
        console.error('❌ 代拿员认证失败:', error);
        res.status(500).json({
            success: false,
            errorCode: 5001,
            errorMessage: '认证失败: ' + error.message
        });
    }
});

// 代拿员信息路由
router.get('/:id', async (req, res) => {
    try {
        const courierId = req.params.id;
        console.log(`📦 获取代拿员信息，ID: ${courierId}`);

        // 查询代拿员信息
        const [couriers] = await db.execute(
            `SELECT cu.*, u.nickname, u.avatar_url, u.phone
             FROM courier_users cu
             LEFT JOIN users u ON cu.user_id = u.id
             WHERE cu.user_id = ?`,
            [courierId]
        );

        if (couriers.length === 0) {
            return res.json({
                success: false,
                message: '代拿员不存在'
            });
        }

        res.json({
            success: true,
            data: couriers[0]
        });

    } catch (error) {
        console.error('❌ 获取代拿员信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取代拿员信息失败'
        });
    }
});

// 切换接单状态
router.post('/toggle-accepting', async (req, res) => {
    try {
        const { userId, isAccepting } = req.body;

        console.log(`🔄 切换接单状态，用户ID: ${userId}, 状态: ${isAccepting}`);

        // 更新接单状态
        await db.execute(
            'UPDATE courier_users SET status = ? WHERE user_id = ?',
            [isAccepting ? 1 : 0, userId]
        );

        res.json({
            success: true,
            message: isAccepting ? '开始接单' : '暂停接单'
        });

    } catch (error) {
        console.error('❌ 切换接单状态失败:', error);
        res.status(500).json({
            success: false,
            message: '操作失败'
        });
    }
});

// 获取代拿员绩效（基于订单实时统计，status = 5 视为已完成，并统计多时间段收入）
router.get('/performance/:userId', async (req, res) => {
    try {
        const { userId } = req.params;

        console.log(`📊 获取代拿员绩效，用户ID: ${userId}`);

        // 基于 orders 实时统计总单量、完成单量、效率及各时间段收入，评分仍使用 courier_users.avg_rating
        const [rows] = await db.execute(
            `SELECT 
                COALESCE(COUNT(o.id), 0) AS totalOrders,
                COALESCE(SUM(CASE WHEN o.status = 5 THEN 1 ELSE 0 END), 0) AS completedOrders,
                COALESCE(cu.avg_rating, 0) AS avgRating,
                -- 总收入（所有已完成订单）
                COALESCE(SUM(CASE 
                    WHEN o.status = 5 THEN o.final_fee 
                    ELSE 0 
                END), 0) AS totalIncome,
                -- 本周收入（按 ISO 周）
                COALESCE(SUM(CASE 
                    WHEN o.status = 5 
                     AND YEARWEEK(COALESCE(o.completed_at, o.delivered_at, o.created_at), 1) = YEARWEEK(CURDATE(), 1)
                    THEN o.final_fee ELSE 0 END), 0) AS weekIncome,
                -- 本月收入
                COALESCE(SUM(CASE 
                    WHEN o.status = 5 
                     AND YEAR(COALESCE(o.completed_at, o.delivered_at, o.created_at)) = YEAR(CURDATE())
                     AND MONTH(COALESCE(o.completed_at, o.delivered_at, o.created_at)) = MONTH(CURDATE())
                    THEN o.final_fee ELSE 0 END), 0) AS monthIncome,
                -- 本季收入
                COALESCE(SUM(CASE 
                    WHEN o.status = 5 
                     AND YEAR(COALESCE(o.completed_at, o.delivered_at, o.created_at)) = YEAR(CURDATE())
                     AND QUARTER(COALESCE(o.completed_at, o.delivered_at, o.created_at)) = QUARTER(CURDATE())
                    THEN o.final_fee ELSE 0 END), 0) AS quarterIncome,
                -- 本年收入
                COALESCE(SUM(CASE 
                    WHEN o.status = 5 
                     AND YEAR(COALESCE(o.completed_at, o.delivered_at, o.created_at)) = YEAR(CURDATE())
                    THEN o.final_fee ELSE 0 END), 0) AS yearIncome,
                -- 平均接单时间（分钟，创建到接单，仅统计已完成且时间完整的订单）
                COALESCE(AVG(CASE 
                    WHEN o.status = 5 
                     AND o.created_at IS NOT NULL 
                     AND o.accepted_at IS NOT NULL 
                    THEN TIMESTAMPDIFF(MINUTE, o.created_at, o.accepted_at) 
                END), 0) AS avgAcceptTime,
                -- 平均配送时间（分钟，接单到送达，仅统计已完成且时间完整的订单）
                COALESCE(AVG(CASE 
                    WHEN o.status = 5 
                     AND o.accepted_at IS NOT NULL 
                     AND o.delivered_at IS NOT NULL 
                    THEN TIMESTAMPDIFF(MINUTE, o.accepted_at, o.delivered_at) 
                END), 0) AS avgDeliveryTime,
                -- 最快配送时间（分钟）
                COALESCE(MIN(CASE 
                    WHEN o.status = 5 
                     AND o.accepted_at IS NOT NULL 
                     AND o.delivered_at IS NOT NULL 
                    THEN TIMESTAMPDIFF(MINUTE, o.accepted_at, o.delivered_at) 
                END), 0) AS fastestDelivery,
                -- 最慢配送时间（分钟）
                COALESCE(MAX(CASE 
                    WHEN o.status = 5 
                     AND o.accepted_at IS NOT NULL 
                     AND o.delivered_at IS NOT NULL 
                    THEN TIMESTAMPDIFF(MINUTE, o.accepted_at, o.delivered_at) 
                END), 0) AS slowestDelivery,
                -- 平均订单收入（仅统计已完成订单）
                COALESCE(AVG(CASE WHEN o.status = 5 THEN o.final_fee END), 0) AS avgOrderIncome,
                -- 最高订单收入
                COALESCE(MAX(CASE WHEN o.status = 5 THEN o.final_fee END), 0) AS maxOrderIncome,
                -- 最低订单收入
                COALESCE(MIN(CASE WHEN o.status = 5 THEN o.final_fee END), 0) AS minOrderIncome,
                -- 最近一周日均收入（按 weekIncome / 7 近似）
                COALESCE(SUM(CASE 
                    WHEN o.status = 5 
                     AND YEARWEEK(COALESCE(o.completed_at, o.delivered_at, o.created_at), 1) = YEARWEEK(CURDATE(), 1)
                    THEN o.final_fee ELSE 0 END) / 7, 0) AS dailyAvgIncome
             FROM courier_users cu
             LEFT JOIN orders o ON o.courier_user_id = cu.id
             WHERE cu.user_id = ?`,
            [userId]
        );

        const row = rows && rows.length > 0 ? rows[0] : null;

        const totalOrders = row ? Number(row.totalOrders || 0) : 0;
        const completedOrders = row ? Number(row.completedOrders || 0) : 0;
        const avgRating = row ? Number(row.avgRating || 0).toFixed(2) : '0.00';
        const completionRate = totalOrders > 0
            ? Number(((completedOrders / totalOrders) * 100).toFixed(2))
            : 0;

        const stats = {
            totalOrders,
            completedOrders,
            avgRating,
            completionRate,

            // 收入汇总
            totalIncome: row ? Number(row.totalIncome || 0) : 0,
            weekIncome: row ? Number(row.weekIncome || 0) : 0,
            monthIncome: row ? Number(row.monthIncome || 0) : 0,
            quarterIncome: row ? Number(row.quarterIncome || 0) : 0,
            yearIncome: row ? Number(row.yearIncome || 0) : 0,

            // 效率与收入分析
            avgAcceptTime: row ? Number(row.avgAcceptTime || 0) : 0,
            avgDeliveryTime: row ? Number(row.avgDeliveryTime || 0) : 0,
            fastestDelivery: row ? Number(row.fastestDelivery || 0) : 0,
            slowestDelivery: row ? Number(row.slowestDelivery || 0) : 0,
            avgOrderIncome: row ? Number(row.avgOrderIncome || 0) : 0,
            maxOrderIncome: row ? Number(row.maxOrderIncome || 0) : 0,
            minOrderIncome: row ? Number(row.minOrderIncome || 0) : 0,
            dailyAvgIncome: row ? Number(row.dailyAvgIncome || 0) : 0
        };

        res.json({
            success: true,
            data: stats
        });

    } catch (error) {
        console.error('❌ 获取绩效失败:', error);
        res.status(500).json({
            success: false,
            message: '获取绩效失败'
        });
    }
});

// 获取代拿员收入
router.get('/income/:userId', async (req, res) => {
    try {
        const { userId } = req.params;

        console.log(`💰 获取代拿员收入，用户ID: ${userId}`);

        // 查询代拿员收入数据：按完成时间优先，其次送达时间，最后创建时间统计
        const [income] = await db.execute(
            `SELECT 
        COALESCE(SUM(o.final_fee), 0) as total,
        COALESCE(SUM(CASE 
          WHEN DATE(COALESCE(o.completed_at, o.delivered_at, o.created_at)) = CURDATE() 
          THEN o.final_fee ELSE 0 END), 0) as today,
        COALESCE(SUM(CASE 
          WHEN YEAR(COALESCE(o.completed_at, o.delivered_at, o.created_at)) = YEAR(CURDATE()) 
           AND MONTH(COALESCE(o.completed_at, o.delivered_at, o.created_at)) = MONTH(CURDATE()) 
          THEN o.final_fee ELSE 0 END), 0) as month,
        0 as available
       FROM orders o
       JOIN courier_users cu ON o.courier_user_id = cu.id
       WHERE cu.user_id = ? AND o.status = 5`,
            [userId]
        );

        const incomeData = income.length > 0 ? income[0] : {
            total: 0,
            today: 0,
            month: 0,
            available: 0
        };

        res.json({
            success: true,
            data: incomeData
        });

    } catch (error) {
        console.error('❌ 获取收入失败:', error);
        res.status(500).json({
            success: false,
            message: '获取收入失败'
        });
    }
});

// 获取代拿员信用分
router.get('/credit/:userId', async (req, res) => {
    try {
        const { userId } = req.params;

        console.log(`⭐ 获取代拿员信用分，用户ID: ${userId}`);

        // 查询代拿员信用分，返回值封顶 100
        const [credit] = await db.execute(
            'SELECT LEAST(credit_score, 100) as score FROM courier_users WHERE user_id = ?',
            [userId]
        );

        const creditScore = credit.length > 0 ? credit[0].score : 100;

        res.json({
            success: true,
            data: {
                score: creditScore,
                trend: 'flat',
                change: 0
            }
        });

    } catch (error) {
        console.error('❌ 获取信用分失败:', error);
        res.status(500).json({
            success: false,
            message: '获取信用分失败'
        });
    }
});

module.exports = router;
